package com.guigu.auth.controller.wx;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.guigu.auth.entity.AuthUser;
import com.guigu.auth.service.AuthUserService;
import com.guigu.auth.utils.ConstantWxUtils;
import com.guigu.auth.utils.HttpClientUtils;
import com.guigu.commons.utils.JwtUtils;
import com.guigu.tms.exception.TmsException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;

/**
 * @ClassName:WxApiController
 * @Description:
 * @Author:longtao
 * @Date:2021/8/7
 * @Version:1.0
 */
@Api(tags = "微信登录!")
@Controller//注意这里没有配置 @RestController
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private AuthUserService authUserService;

    /**
     * 生成微信二维码
     */
    @GetMapping("/login")
    @ApiOperation("微信生成二维码!")
    public String getWxCode() {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //回调地址
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;//获取服务器重定向地址
        String s = null;
        try {
            s = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //请求微信地址
        String url = String.format(baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                s,
                "hnguigu"
        );
        return "redirect:" + url;
    }

    /**
     * 获取扫描人信息,添加数据
     *
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/callback")
    @ApiOperation("获取扫描人信息,添加数据!")
    public String callback(@ApiParam(name = "code", value = "唯一id,用于请求微信固定地址获取扫描人信息)")
                                   String code,
                           @ApiParam(name = "state", value = "原样传递")
                                   String state) {
        //获取code值
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String s = String.format(baseAccessTokenUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code);
        String result = null;
        try {
            //调用微信固定接口,返回一个json值
            result = HttpClientUtils.get(s);
        } catch (Exception e) {
            e.printStackTrace();
            throw new TmsException("2001", "获取access_token失败!");
        }
        System.out.println("result = " + result);
        //解析json
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap map = null;
            map = objectMapper.readValue(result, HashMap.class);
            String accessToken = (String) map.get("access_token");
            String openid = (String) map.get("openid");
            if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openid)) {
                throw new TmsException("2001", "accessToken和openid为空!");
            }
            //查询当前用户是否曾经使用过微信登录
            AuthUser user = authUserService.getByOpenId(openid);
            if (ObjectUtils.isEmpty(user)) {
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                String resultUserInfo = null;
                //获取从微信获取到的用户信息
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultUserInfo = " + resultUserInfo);
                //解析json
                HashMap<String, Object> mapUserInfo = objectMapper.readValue(resultUserInfo, HashMap.class);
                String nickname = (String) mapUserInfo.get("nickname");
                String headimgurl = (String) mapUserInfo.get("headimgurl");
                int sex = (int) mapUserInfo.get("sex");
                //使用this.$route.query.token接收我们的参数,来进行验证是否可以登录!
                AuthUser authUser = new AuthUser();
                authUser.setOpenId(openid);
                authUser.setName(nickname);
                authUser.setSex(sex == 0 ? "M" : "W");
                authUser.setAvatar(headimgurl);
                authUser.setCreateTime(new Date());
                authUserService.save(authUser);
                String token = JwtUtils.getJwtToken(String.valueOf(authUser.getId()), nickname);
                //使用this.$route.query.token接收我们的参数,来进行验证是否可以登录!
                return "redirect:http://localhost:9527/#/login?token="+token;

            } else {
                /**
                 * 如果有则切换为登录
                 */
                String token = JwtUtils.getJwtToken(String.valueOf(user.getId()),user.getName());
                //使用this.$route.query.token接收我们的参数,来进行验证是否可以登录!
                return "redirect:http://localhost:9527/#/login?token=" + token;
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new TmsException("2001", "第三方登录失败!");
        }
    }
}
